<template>
  <div class="store-basics-edit-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>{{ title }}</span>
      </div>
      <el-form ref="form" id="form" :model="form" :rules="rules" label-width="135px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="分类名称" prop="catName">
              <el-input v-model="form.catName" placeholder="请输入分类名称" />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="关联父级分类" prop="parentId">
              <el-select v-model="form.parentId" placeholder="请选择关联父级分类">
                <el-option v-for="dict in categoryList" :key="dict.id" :label="dict.catName" :value="dict.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col> -->
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="分类排序" prop="sort">
              <el-input v-model="form.sort" placeholder="请输入分类名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="是否展示">
              <el-select v-model="form.isShow" placeholder="请选择是否展示">
                <el-option v-for="dict in isShowOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <div class="info-div main-pic">
          <div class="div-title">分类小图标</div>
          <div class="pic-div">
            <el-upload :action="uploadActionMainMin" :headers="uploadHeaders" :multiple="false" :file-list="mainPicMin" list-type="picture-card" :on-success="handleUploadSuccMainMin">
              <i slot="default" class="el-icon-plus"></i>
              <div slot="file" slot-scope="{ file }">
                <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
                <span class="el-upload-list__item-actions">
                  <span class="el-upload-list__item-preview" @click="handlePicPreview(file)">
                    <i class="el-icon-zoom-in"></i>
                  </span>
                  <span class="el-upload-list__item-delete" @click="handlePicRemove(file, mainPicMin)">
                    <i class="el-icon-delete"></i>
                  </span>
                </span>
              </div>
            </el-upload>
          </div>
        </div>
        <div class="info-div main-pic">
          <div class="div-title">分类图片</div>
          <div class="pic-div">
            <el-upload :action="uploadActionMain" :headers="uploadHeaders" :multiple="false" :file-list="mainPic" list-type="picture-card" :on-success="handleUploadSuccMain">
              <i slot="default" class="el-icon-plus"></i>
              <div slot="file" slot-scope="{ file }">
                <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
                <span class="el-upload-list__item-actions">
                  <span class="el-upload-list__item-preview" @click="handlePicPreview(file)">
                    <i class="el-icon-zoom-in"></i>
                  </span>
                  <span class="el-upload-list__item-delete" @click="handlePicRemove(file, mainPic)">
                    <i class="el-icon-delete"></i>
                  </span>
                </span>
              </div>
            </el-upload>
          </div>
        </div>
        <el-row :gutter="20">
          <el-form-item class="form-btn-bar">
            <el-button type="primary" @click="submitForm">保 存</el-button>
          </el-form-item>
        </el-row>
      </el-form>
    </el-card>

    <el-dialog :visible.sync="showPicPreview">
      <img width="100%" :src="picPreviewUrl" alt="" />
    </el-dialog>
  </div>
</template>

<script>
import Editor from '@/components/Editor'
import { getCategory, addCategory, updateCategory } from '@/api/category/category'
import { addFile, delFiles, getFileList, editFile, getPreId } from '@/api/basic/file'

export default {
  name: 'ProjectEdit',
  components: {
    Editor
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 标题
      title: '',
      // 商品分类表格数据
      // categoryList: [],
      uploadActionMain: '',
      uploadActionMainMin: '',
      uploadHeaders: {
        Authorization: 'Bearer ' + this.$store.state.user.token,
        lesseeId: this.$store.state.user.lesseeid || '13'
      },
      // 是否展示字典
      isShowOptions: [],
      mainPic: [],
      mainPicMin: [],
      showPicPreview: false,
      picPreviewUrl: '',
      // 是否显示弹出层
      open: false,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        catName: [
          {
            required: false,
            message: '请填写商品分类',
            trigger: 'blur'
          }
        ],
        sort: [
          {
            required: false,
            message: '请写分类排序',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  created() {
    this.getDicts('is_active').then(response => {
      this.isShowOptions = response.data
    })
    const that = this
    // that.getList();
    that.reset(function() {
      that.getCategoryInfo(that.$route.params.id)
    })
  },
  methods: {
    handlePicPreview(file) {
      this.picPreviewUrl = file.url
      this.showPicPreview = true
    },

    handlePicRemove(file, fileList) {
      return this.$confirm('确定删除该图片?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          let fileId = file.id || file.response.fileId
          if (fileId) {
            delFiles({
              ids: fileId
            }).then(response => {
              if (response.code !== 200) {
                this.msgError(response.msg)
              } else {
                let findIndex = fileList.findIndex(obj => {
                  return obj.uid == file.uid
                })
                if (findIndex >= 0) {
                  fileList.splice(findIndex, 1)
                }
              }
            })
          } else {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            let findIndex = fileList.findIndex(obj => {
              return obj.uid == file.uid
            })
            if (findIndex >= 0) {
              fileList.splice(findIndex, 1)
            }
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },

    editFile(file, sorting) {
      editFile(
        {
          id: file.id || file.response.fileId,
          sorting
        },
        res => {}
      )
    },
    /** 查询商品分类列表 */
    // getList() {
    //   this.loading = true;
    //   listCategoryAll({}).then(response => {
    //     this.categoryList = response.data;
    //     this.loading = false;
    //   });
    // },
    handleUploadSuccMain(response, file, fileList) {
      if (this.mainPic.length) {
        let fileId = this.mainPic[0].id || this.mainPic[0].response.fileId
        delFiles({
          ids: fileId
        }).then(response => {})
      }
      console.log('上传的文件:')
      console.log(file)
      this.mainPic = [file]
      this.form.iconImg = response.url
    },
    handleUploadSuccMainMin(response, file, fileList) {
      if (this.mainPicMin.length) {
        let fileId = this.mainPicMin[0].id || this.mainPicMin[0].response.fileId
        delFiles({
          ids: fileId
        }).then(response => {})
      }
      console.log('上传的min文件:')
      console.log(file)
      this.mainPicMin = [file]
      this.form.iconMiniImg = response.url
    },
    setUploadAction(id) {
      this.uploadActionMain = process.env.VUE_APP_BASE_API + '/common/upload/category?sourcessId=' + id + '&sourcessType=CATEGORY&isActive=是'
      this.uploadActionMainMin = process.env.VUE_APP_BASE_API + '/common/upload/category?sourcessId=' + id + '&sourcessType=CATEGORY_ICON&isActive=是'
    },
    /** 提交按钮 */
    submitForm: function() {
      const that = this
      that.$refs['form'].validate(valid => {
        if (valid) {
          if (that.title == '修改商品分类') {
            updateCategory(that.form).then(response => {
              if (response.code === 200) {
                that.msgSuccess('修改成功')
                that.open = false
                that.closeSelectedTag(that.$route)
              }
            })
          } else {
            addCategory(that.form).then(response => {
              if (response.code === 200) {
                that.msgSuccess('新增成功')
                that.open = false
                that.closeSelectedTag(that.$route)
              }
            })
          }
        }
      })
    },
    isActive(route) {
      return route.path === this.$route.path
    },
    closeSelectedTag(view) {
      this.$store.dispatch('tagsView/delView', view).then(({ visitedViews }) => {
        if (this.isActive(view)) {
          this.toLastView(visitedViews, view)
        }
      })
    },
    toLastView(visitedViews, view) {
      const latestView = visitedViews.slice(-1)[0]
      if (latestView) {
        this.$router.push(latestView.fullPath)
      } else {
        if (view.name === 'Dashboard') {
          this.$router.replace({
            path: '/redirect' + view.fullPath
          })
        } else {
          this.$router.push('/')
        }
      }
    },
    getCategoryInfo(id) {
      const that = this
      if (id != 'new') {
        getCategory(id).then(response => {
          that.form = response.data
          that.setUploadAction(that.form.id)
          // 根据url创建文件对象：
          if (that.form.iconImg) {
            // 获取图片
            console.log('sourcessId：' + that.form.id)
            getFileList({ sourcessId: that.form.id, sourcessType: 'CATEGORY' }).then(rs => {
              if (rs.code == 200) {
                that.mainPic = rs.data || rs.rows || []
                if (that.mainPic.length > 0) {
                  that.mainPic.forEach(function(item) {
                    item.url = item.fileFullUrl
                  })
                }
              }
            })
          }
          // 根据url创建文件对象：
          if (that.form.iconMiniImg) {
            // 获取图片
            console.log('sourcessId：' + that.form.id)
            getFileList({ sourcessId: that.form.id, sourcessType: 'CATEGORY_ICON' }).then(rs => {
              if (rs.code == 200) {
                that.mainPicMin = rs.data || rs.rows || []
                if (that.mainPicMin.length > 0) {
                  that.mainPicMin.forEach(function(item) {
                    item.url = item.fileFullUrl
                  })
                }
              }
            })
          }
          that.title = '修改商品分类'
        })
      } else {
        that.getPreIdFn()
        that.title = '添加商品分类'
      }
    },
    getPreIdFn() {
      const that = this
      // 文件上传: 新增记录提交前，获取预定的记录id, 提交时要提交此预定的记录id
      getPreId({}).then(response => {
        if (response.code === 200) {
          const data = response.data
          if (data.id) {
            that.setUploadAction(data.id)
            that.form.id = data.id
            console.log('preId:' + that.form.id)
          }
        }
      })
    },
    // 表单重置
    reset(call) {
      this.form = {
        id: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        isActive: '1',
        lesseeId: '13',
        catName: undefined,
        parentId: undefined,
        sort: undefined,
        isShow: '1',
        iconImg: undefined,
        iconMiniImg: undefined
      }
      this.resetForm('form')
      if (call) {
        call()
      }
    }
  }
}
</script>

<style>
.editor-content .quill-editor.editor {
  height: 500px;
}

.form-btn-bar {
  margin-top: 30px;
  text-align: center;
}

/*搜索框*/
.search {
  width: 100%;
}

.input-group {
  position: relative;
  display: table;
  border-collapse: separate;
}

* {
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
}

.btn {
  display: inline-block;
  padding: 6px 12px;
  margin-bottom: 0;
  font-size: 14px;
  font-weight: 400;
  line-height: 1.42857143;
  text-align: center;
  white-space: nowrap;
  vertical-align: middle;
  -ms-touch-action: manipulation;
  touch-action: manipulation;
  cursor: pointer;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
  background-image: none;
  border: 1px solid transparent;
  border-radius: 4px;
}

.form-control {
  display: block;
  width: 100%;
  height: 34px;
  padding: 6px 12px;
  font-size: 14px;
  line-height: 1.42857143;
  color: #555;
  background-color: #fff;
  background-image: none;
  border: 1px solid #ccc;
  border-radius: 4px;
  -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
  box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
  -webkit-transition: border-color ease-in-out 0.15s, -webkit-box-shadow ease-in-out 0.15s;
  -o-transition: border-color ease-in-out 0.15s, box-shadow ease-in-out 0.15s;
  transition: border-color ease-in-out 0.15s, box-shadow ease-in-out 0.15s;
}

.input-group .form-control:first-child,
.input-group-addon:first-child,
.input-group-btn:first-child > .btn,
.input-group-btn:first-child > .btn-group > .btn,
.input-group-btn:first-child > .dropdown-toggle,
.input-group-btn:last-child > .btn-group:not(:last-child) > .btn,
.input-group-btn:last-child > .btn:not(:last-child):not(.dropdown-toggle) {
  border-top-right-radius: 0;
  border-bottom-right-radius: 0;
}

.input-group .form-control,
.input-group-addon,
.input-group-btn {
  display: table-cell;
}

.input-group .form-control {
  position: relative;
  z-index: 2;
  float: left;
  width: 100%;
  margin-bottom: 0;
}

button,
input,
select,
textarea {
  font-family: inherit;
  font-size: inherit;
  line-height: inherit;
}

button,
input,
optgroup,
select,
textarea {
  margin: 0;
  font: inherit;
  color: inherit;
}

.info-div {
  padding: 20px 20px 20px 65px;
}

.pic-div {
  border: 1px dotted #9e9e9e;
  border-radius: 10px;
  padding: 10px;
}

.div-title {
  margin-bottom: 20px;
  font-size: 14px;
  font-weight: 700;
  color: #606266;
}

.describe-pic .el-upload-list--picture-card .el-upload-list__item {
  display: block;
  width: 50%;
  height: auto;
  margin: 0;
  border: none;
  border-radius: 0;
}

.describe-pic .el-upload-list--picture-card .el-upload-list__item-thumbnail {
  vertical-align: top;
}

.describe-pic .el-upload--picture-card {
  margin-top: 20px;
  width: 50%;
  height: auto;
}

.el-dialog__body {
  padding: 10px 20px 30px 20px;
}

.attrs-btn-div {
  text-align: center;
  margin-top: 30px;
}

.goods-attrs-btn-bar {
  text-align: right;
  margin-bottom: 20px;
}

.input-group .form-control.getAddress {
  width: 85%;
}

.searchBtn {
  width: 15%;
  float: right;
  border-radius: 0 4px 4px 0;
  background: #dca131;
  color: #fff;
}

/*提示语*/
.prompt {
  color: #e84720;
  font-size: 14px;
  font-family: '微软雅黑';
  margin: 5px 10px;
}

.validate {
  position: absolute;
  bottom: 10px;
  right: 20px;
  color: #e84720;
}

.test {
  display: inline-block;
  width: 20px;
  height: 10px;
  background: rgba(239, 194, 192, 0.38);
}

/*地图*/
.map {
  padding: 10px 30px;
  border: 1px solid #ddd;
  border-radius: 10px;
  margin-bottom: 20px;
}

#containerMap {
  margin: 10px auto;
  width: 100%;
  min-height: 470px;
}

/*经纬度设置*/
.latLng {
  text-align: center;
  margin: 20px auto;
}

.latlngSpan {
  font-size: 16px;
}

.latlngInput {
  width: 200px;
  height: 25px;
  outline: none;
  background: #fff;
}
</style>
